package cn.cimoc.service.impl;

import cn.cimoc.mapper.AddressMapper;
import cn.cimoc.mapper.CartMapper;
import cn.cimoc.mapper.OrderMapper;
import cn.cimoc.mapper.TOrderItemMapper;
import cn.cimoc.model.dto.output.CartDTO;
import cn.cimoc.model.po.TAddress;
import cn.cimoc.model.po.TCart;
import cn.cimoc.model.po.TOrder;
import cn.cimoc.model.po.TOrderItem;
import cn.cimoc.service.OrderService;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Arrays;

/**
 * @author LGZ
 * @date 2022/7/16 15:58
 * <p>
 */
@Service
public class OrderServiceImpl implements OrderService {

    @Autowired
    OrderMapper mapper;

    @Autowired
    AddressMapper aMapper;

    @Autowired
    CartMapper cMapper;

    @Autowired
    TOrderItemMapper tMapper;

    @Override
    public void create(Long aid, Long[] cids, long uid, String username) {
        TOrder tOrder = new TOrder();
        tOrder.setUid(uid);
        tOrder.setCreatedUser(username);
        tOrder.setModifiedUser(username);
        tOrder.setStatus(0L);

        TAddress address = aMapper.selectById(aid);
        tOrder.setRecvProvince(address.getProvinceName());
        tOrder.setRecvCity(address.getCityName());
        tOrder.setRecvArea(address.getAreaName());
        tOrder.setRecvAddress(address.getAddress());
        tOrder.setRecvName(address.getReceiver());
        tOrder.setRecvPhone(address.getPhone());

        CartDTO[] cart = cMapper.getCartByCid(cids);
        TOrderItem[] items = new TOrderItem[cart.length];
        long totalPrice = 0L;
        for (int i = 0; i < cart.length; i++) {
            totalPrice += cart[i].getRealPrice() * cart[i].getNum();
            items[i] = new TOrderItem();
            items[i].setImage(cart[i].getImage());
            items[i].setNum(cart[i].getNum());
            items[i].setPid(cart[i].getPid());
            items[i].setPrice(cart[i].getRealPrice());
            items[i].setTitle(cart[i].getTitle());
            items[i].setCreatedUser(username);
            items[i].setModifiedUser(username);
        }

        tOrder.setPrice(totalPrice);
        mapper.insert(tOrder);

        for (TOrderItem item : items) {
            item.setOid(tOrder.getOid());
            tMapper.insert(item);
        }

        UpdateWrapper<TCart> wrapper = new UpdateWrapper<>();
        wrapper.in("cid", Arrays.asList(cids));
        cMapper.delete(wrapper);
    }
}
